/**
 * 目标：访问路径不存在时，返回结果中包含请求路径path
    实现：1、创建一个异常过滤器，负责将捕获作为HttpException类实例的异常
        2、访问底层平台Request、Response，通过访问Request对象，
            提取原始url将其包含在日志信息中
        3、使用Response.jon()方法，使用Response对象直接控制发送的响应
 * 
 */


import { ArgumentsHost, ExceptionFilter, Catch, HttpException, HttpStatus } from "@nestjs/common";
import { Request, Response } from "express";
import { BusinessException } from "./business.exception.filter";
@Catch(HttpException)
export class HttpExceptionFilter implements ExceptionFilter {
    catch(exception: HttpException, host: ArgumentsHost) {
        const ctx = host.switchToHttp();
        const request = ctx.getRequest < Request > ();
        const response = ctx.getResponse < Response > ();
        const status = exception.getStatus();

        // 处理业务异常
        if (exception instanceof BusinessException) {
            const error = exception.getResponse();
            response.status(HttpStatus.OK).send({
                data: null,
                status: error['code'],
                extra: {},
                message: error['message'],
                success: false,
            });
            return;
        }

        //  HTTP 异常的处理。
        response.status(status).json({
            data: exception.message,
            time: new Date().getTime(),
            success: false,
            path: request.url,
            code: status
        });
    }
}
